package smap;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

import BD.DisciplinaBD;
import DAO.DisciplinaDAO;
import BD.AreaBD;
import DAO.AreaDAO;


public class TelaCadDisciplina extends javax.swing.JDialog {
    
    DisciplinaBD dis = new DisciplinaBD();
    DisciplinaDAO disDao = new DisciplinaDAO();
    
    //carregar combobox area
    AreaDAO areDao = new AreaDAO();
    List<AreaBD> listaarea = new ArrayList<AreaBD>();
    
    //verificar se é cadastro ou alteração. boolean = cadsatro, false = alteração
    private boolean cadastrar;
    
    public boolean isCadastrar() {
        return cadastrar;
    }

    public void setCadastrar(boolean cadastrar) {
        this.cadastrar = cadastrar;
    }
    
    public TelaCadDisciplina(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblNome = new javax.swing.JLabel();
        lblCargaHoraria = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        txtNome = new javax.swing.JTextField();
        lblTipo = new javax.swing.JLabel();
        cmbTipoDisciplina = new javax.swing.JComboBox();
        txtCargaHoraria = new javax.swing.JFormattedTextField();
        btnTelaArea = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        cmbArea = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        txtCreditos = new javax.swing.JFormattedTextField();
        pnlVoltar = new javax.swing.JPanel();
        btnVoltar = new javax.swing.JButton();
        btnCadastrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Disciplina");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(192, 192, 192)));

        lblNome.setText("* Nome:");

        lblCargaHoraria.setText("* Carga Horaria:");

        lblCodigo.setText("* Código:");

        txtCodigo.setEnabled(false);

        lblTipo.setText("Tipo Disciplina:");

        cmbTipoDisciplina.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Obrigatoria", "Eletiva" }));

        txtCargaHoraria.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));

        btnTelaArea.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/area-icon.png"))); // NOI18N
        btnTelaArea.setToolTipText("Adicionar nova área");
        btnTelaArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTelaAreaActionPerformed(evt);
            }
        });

        jLabel1.setText("* Área:");

        jLabel2.setText("* Créditos:");

        txtCreditos.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblNome, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblCodigo, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(4, 4, 4)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNome)
                            .addComponent(txtCodigo)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblTipo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmbTipoDisciplina, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblCargaHoraria)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCargaHoraria))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(cmbArea, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnTelaArea))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtCreditos, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCodigo)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNome)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCargaHoraria)
                    .addComponent(txtCargaHoraria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTipo)
                    .addComponent(cmbTipoDisciplina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtCreditos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnTelaArea)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cmbArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addContainerGap())
        );

        pnlVoltar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(192, 192, 192)));

        btnVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/voltar-icon.png"))); // NOI18N
        btnVoltar.setText("Voltar");
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlVoltarLayout = new javax.swing.GroupLayout(pnlVoltar);
        pnlVoltar.setLayout(pnlVoltarLayout);
        pnlVoltarLayout.setHorizontalGroup(
            pnlVoltarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlVoltarLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(98, 98, 98))
        );
        pnlVoltarLayout.setVerticalGroup(
            pnlVoltarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlVoltarLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnCadastrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/add-icon.png"))); // NOI18N
        btnCadastrar.setText("Cadastrar");
        btnCadastrar.setPreferredSize(new java.awt.Dimension(61, 23));
        btnCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCadastrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlVoltar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(93, Short.MAX_VALUE)
                .addComponent(btnCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(90, 90, 90))
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents
        
    public void carregarComboArea(){
        listaarea = areDao.carregarComboArea();
        
        for(int i = 0; i<listaarea.size(); i++){
            cmbArea.addItem(listaarea.get(i).getNome());
        }
    }
    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
        this.dispose(); // Fecha Tela de Cadastro de Disciplina
    }//GEN-LAST:event_btnVoltarActionPerformed

    private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCadastrarActionPerformed
       if(txtNome.getText().trim().length() == 0 || txtCargaHoraria.getText().trim().length() == 0 ||
             txtCreditos.getText().trim().length() == 0  || cmbArea.getSelectedIndex() == -1 || cmbArea.getSelectedIndex() == 0 || Integer.parseInt(txtCreditos.getText()) < 0
               || Integer.parseInt(txtCargaHoraria.getText()) < 0){
           
            if(txtCargaHoraria.getText().trim().length() != 0){
              if(Integer.parseInt(txtCargaHoraria.getText()) < 0)
                txtCargaHoraria.setText("");
            }
            
            if(txtCreditos.getText().trim().length() != 0){
              if(Integer.parseInt(txtCreditos.getText()) < 0)
                txtCreditos.setText("");
            }


            JOptionPane.showMessageDialog(null,"Campos nome, carga horaria, créditos e área são obrigatórios", 
                    "Campos Obrigatórios", JOptionPane.INFORMATION_MESSAGE);
      
       }
       
       
       else{
            dis.setCodigo(Integer.parseInt(txtCodigo.getText()));
            dis.setNome(txtNome.getText().trim());            
            dis.setCargahoraria(Integer.parseInt(txtCargaHoraria.getText().toString()));
            dis.setTipodisciplina(cmbTipoDisciplina.getSelectedItem().toString());
            dis.setCreditos(Integer.parseInt(txtCreditos.getText().toString()));
            dis.setCodArea(listaarea.get(cmbArea.getSelectedIndex()).getCodigo());
            
            if(isCadastrar()){ //cadastrar
                if(disDao.inserirDisciplina(dis)){
                    // Auto Incremento
                    autoIncremento();
                    
                    //limpar campos
                    txtNome.setText("");
                    txtCargaHoraria.setText("");
                    txtCreditos.setText("");
                }
            }else{ //alterar
                if(disDao.alterarDisciplina(dis)){//Envia a Instancia e obtem a resposta
                    this.dispose();
                }
            }
       }
    }//GEN-LAST:event_btnCadastrarActionPerformed

    private void btnTelaAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTelaAreaActionPerformed
        this.setEnabled(false); //trava tela cadDisciplina
        TelaArea telarea = new TelaArea(null, true);
        telarea.carregarTabela(); //carrega tabela da tela área
        telarea.setVisible(true); //abre tela Area
        cmbArea.removeAllItems(); //limpa combo
        listaarea.removeAll(listaarea);
        carregarComboArea(); //recarrega combo com as áreas
        this.setEnabled(true);
    }//GEN-LAST:event_btnTelaAreaActionPerformed
        
    //Método para alterar
    public void recebeObjejo (DisciplinaBD ds){
        txtCodigo.setText(String.valueOf(ds.getCodigo()));
        txtNome.setText(ds.getNome());
        txtCargaHoraria.setText(String.valueOf(ds.getCargahoraria()));
        cmbTipoDisciplina.setSelectedItem(ds.getTipodisciplina());  
        txtCreditos.setText(String.valueOf(ds.getCreditos()));
        cmbArea.setSelectedItem(ds.getNomeArea());
    }
    
    //Método para visualizar
    public void visualizaObjeto(DisciplinaBD ds){
        //Setar os valores recebidos
        recebeObjejo(ds);  
        
        //Travando os campos de texto e botão
        txtCodigo.setEnabled(false);
        txtNome.setEnabled(false);
        txtCargaHoraria.setEnabled(false);
        txtCreditos.setEnabled(false);
        cmbTipoDisciplina.setEnabled(false);
        btnCadastrar.setEnabled(false);
        cmbArea.setEnabled(false);
        btnTelaArea.setEnabled(false);
    }  
    
    public void autoIncremento(){
        txtCodigo.setText(String.valueOf(disDao.autoIncremento()));          
    }
    
    public static void main(String args[]) {
        
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaCadDisciplina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaCadDisciplina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaCadDisciplina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaCadDisciplina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>


        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                TelaCadDisciplina dialog = new TelaCadDisciplina(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCadastrar;
    private javax.swing.JButton btnTelaArea;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JComboBox cmbArea;
    private javax.swing.JComboBox cmbTipoDisciplina;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblCargaHoraria;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblTipo;
    private javax.swing.JPanel pnlVoltar;
    private javax.swing.JFormattedTextField txtCargaHoraria;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JFormattedTextField txtCreditos;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables
}
